from rest_framework import serializers

from areas.models import Area
from user.models import Address
import re

class AreasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ('id', 'name')




class AddressSerializer(serializers.ModelSerializer):
    # 只读，就是序列化输出的时候，只需要读取就行
    province = serializers.StringRelatedField(label='省',read_only=True)
    city = serializers.StringRelatedField(label='市',read_only=True)
    district = serializers.StringRelatedField(label='区',read_only=True)
    # 反序列化，就是/home/python/Desktop/managerr/client.conf返回给前端，不能返回后台．
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)


    class Meta:
        model = Address
        exclude = ('user','is_deleted','create_time','update_time')

    # 验证
    def validate(self, attrs):
        if not re.match(r'^1[3-9]\d{9}$',attrs['mobile']):
            raise serializers.ValidationError('手机号码错误')

        return attrs

    def create(self, validated_data):
        #
        user = self.context['request'].user
        # 赋值给validate_data对象
        validated_data['user'] = user
        # 传入参数，进行新增 这里返回的是一个对象，因此前端代码中有误，需要修改
        addres = super().create(validated_data)

        return addres



